﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace YAWD.Utils
{
	class BitmapFrameConverter : IValueConverter
	{
	    public double DecodePixelWidth { get; set; }

	    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			try
			{
				string path = value as string;

				if (path != null)
				{
					//create new stream and create bitmap frame
					BitmapImage bitmapImage = new BitmapImage();
					bitmapImage.BeginInit();
					bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read);
					bitmapImage.DecodePixelWidth = 200;
					//load the image now so we can immediately dispose of the stream
					bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
					bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
					bitmapImage.EndInit();
                    bitmapImage.Freeze();
					//clean up the stream to avoid file access exceptions when attempting to delete images
					bitmapImage.StreamSource.Dispose();

					return bitmapImage;
				}
				else
					return DependencyProperty.UnsetValue;
			}
			catch (Exception)
			{
                return DependencyProperty.UnsetValue;
			}

		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			return DependencyProperty.UnsetValue;
		}
	}
}
